package com.vol.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.vol.JwtHelper;
import com.vol.AuthParams;
import com.vol.RedisUtils;
import com.vol.entity.Result;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.util.List;


@Component
public class LoginProtectedInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtHelper jwtHelper;
    @Autowired
    private RedisUtils<List<String>> redisUtilsAuth;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // 允许跨域源，全部允许为*，否则写允许请求的源ip
        response.setHeader("Access-Control-Allow-Origin", "*");
        /*
        if (StringUtils.isEmpty(request.getHeader("Origin"))) {
            response.setHeader("Access-Control-Allow-Origin", "*");
        } else {
            response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        }*/

        response.setHeader("Access-Control-Allow-Credentials", "true");
        // 允许跨域方法：全部允许为*，否则写具体的方法，例如：GET, POST, PUT, DELETE, OPTIONS
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Max-Age", "86400");
        // 允许跨域请求头
        response.setHeader("Access-Control-Allow-Headers", "*");


        //从请求头中获取token
        String authorization = request.getHeader("Authorization");
        if(authorization==null || authorization.length()==0){
            response.setStatus(401);
            response.getWriter().print(this.execError(401,"登录权限过期或失效，请重新登录！"));
            return false;
        }
        String token = authorization.replace("Bearer ","");
        //检查是否有效
        boolean expiration = jwtHelper.isExpiration(token);
        //有效放行
        if (expiration){
            response.setStatus(401);
            response.getWriter().print(this.execError(401,"用户token过期！"));
            return false;
        }

        //验证权限
        if(handler instanceof HandlerMethod) {
            HandlerMethod h = (HandlerMethod)handler;
            if(h.getMethodAnnotation(AuthParams.class)!=null){
                String auth = h.getMethodAnnotation(AuthParams.class).value();
                System.out.println("用户想执行的操作是:"+h.getMethodAnnotation(AuthParams.class).value());
                //判断后执行操作...
                Integer userid = jwtHelper.getUserId(token);
                List<String> listAuth = redisUtilsAuth.getKey("listAuth" + userid);
                if(listAuth.contains(auth)){
                    //放行，没有过期
                    return true;
                }else {
                    response.setStatus(403);
                    response.getWriter().print(this.execError(403,"当前账号没有相应权限！"));
                    return false;
                }
            }
        }


        return true;
        /*
        response.setStatus(401);
        response.getWriter().print(this.execError(401,"登录权限过期或失效，请重新登录！"));
        return false;
        */
    }

    /*
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理后，清除ThreadLocal中的数据

    }
     */


    private String execError(int code,String message) throws IOException {
        Result result = Result.build(null,code,message,false);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(result);
        return  json;
    }


}
